# encoding:utf-8
import json
import pickle
import traceback
import logging
from datetime import datetime
from io import BytesIO
import random

from flask import Blueprint, request, g, make_response
from flask_restful import Resource, Api, reqparse, marshal, fields, current_app

from common.utils.custom_output_json import custom_output_json
from common.utils.jwt_util import _generate_token, refresh_token
from common.models import rds, db, cache
from common.models.user import UserBase
from common.model_fields.user_fields import user_fields
from common.utils.utils import generate_code
from common.utils.login_util import check_code

user_bp = Blueprint('user_bp', __name__, url_prefix='/user')
api = Api(user_bp)


@api.representation('application/json')
def output_json(data, code=200, headers=None):
    return custom_output_json(data, code, headers)


class Login(Resource):
    """
    登录
    增加验证码验证
    """

    # TODO
    def post(self):
        pass


class VerificationCode(Resource):
    """
    图片验证码
    """

    def get(self):
        try:
            parser = reqparse.RequestParser()
            args = parser.parse_args()

            # 生成图片验证码
            text, image = generate_code()
            # TODO 需要做什么

            out = BytesIO()
            image.save(out, 'png')
            out.seek(0)
            resp = make_response(out.read())
            resp.content_type = 'image/png'
            return resp
        except:
            error = traceback.format_exc()
            logging.error('code image error{}'.format(error))
            return {'message': 'fail'}, 506


api.add_resource(Login, '/user_login', endpoint='/login')
api.add_resource(VerificationCode, '/user_code', endpoint='user/code')
